import router, { asyncRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist
// 路由前置守卫
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
      return
    }

    if (!store.getters.name) {
      // get user info
      const res = await store.dispatch('user/getUserInfo')
      const filterRoutes = asyncRoutes.filter(item => {
        // return true/false
        return res.roles.menus.includes(item.name)
      }) // 筛选后的路由
      store.commit('user/setRoutes', filterRoutes) // 更新 state 信息
      router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }]) // 添加动态路由信息到路由表
      // router添加动态路由之后 需要转发一下
      next(to.path) // 目的是让路由拥有信息 router的已知缺陷
    }
    next()
    return
  }

  /* has no token*/
  if (whiteList.includes(to.path)) {
    next()
  } else {
    // other pages that do not have permission to access are redirected to the login page.
    next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
})
// 路由后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
